package com.think.common.web.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.think.common.cons.PageCons;
import com.think.common.utils.AntiSqlFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * SuperController
 * </p>
 *
 * @author: xwj
 * @data: 2019-04-06
 */
public class SuperController {

    @Autowired
    private HttpServletRequest request;

    /**
     * 获取分页对象
     *
     * @return com.baomidou.web.extension.plugins.pagination.Page<T>
     * @author xwj
     * @data 2019/4/6
     */
    protected <T> Page<T> getPage() {
        return getPage(false);
    }

    /**
     * 获取分页对象
     *
     * @param openSort 是否获取排序
     * @return com.baomidou.web.extension.plugins.pagination.Page<T>
     * @author xwj
     * @data 2019/4/6
     */
    private <T> Page<T> getPage(boolean openSort) {
        // 页数
        Integer cursor = Convert.toInt(request.getParameter(PageCons.PAGE_PAGE), PageCons.DEFAULT_PAGE);
        // 分页大小
        Integer limit = Convert.toInt(request.getParameter(PageCons.PAGE_ROWS), PageCons.DEFAULT_LIMIT);
        // 是否查询分页
        Boolean searchCount = Convert.toBool(request.getParameter(PageCons.SEARCH_COUNT), true);
        limit = limit > PageCons.MAX_LIMIT ? PageCons.MAX_LIMIT : limit;
        Page<T> page = new Page<>(cursor, limit, searchCount);
        if (openSort) {
            // 过滤，防止sql注入
            page.setAsc(AntiSqlFilter.getSafeValues(request.getParameterValues(PageCons.PAGE_ASCS)));
            page.setDesc(AntiSqlFilter.getSafeValues(request.getParameterValues(PageCons.PAGE_DESCS)));
        }
        return page;
    }
}
